// src/utils/broadcastUtils.ts
type MessageHandler = (data: any) => void;

class BroadcastChannelManager {
  private channel: BroadcastChannel;
  private messageHandlers: Set<MessageHandler> = new Set();

  constructor(channelName: string) {
    this.channel = new BroadcastChannel(channelName);
    this.channel.onmessage = (event: MessageEvent) => {
      this.messageHandlers.forEach(handler => handler(event.data));
    };
  }

  // 发送消息
  postMessage(message: any): void {
    this.channel.postMessage(message);
  }

  // 添加监听
  addMessageHandler(handler: MessageHandler): void {
    this.messageHandlers.add(handler);
  }

  // 移除监听
  removeMessageHandler(handler: MessageHandler): void {
    this.messageHandlers.delete(handler);
  }

  // 关闭频道
  close(): void {
    this.channel.close();
  }
}

// 单例模式确保全局使用同一频道
let instance: BroadcastChannelManager | null = null;

export const getBroadcastInstance = (channelName: string = "vue-app-channel") => {
  if (!instance) {
    instance = new BroadcastChannelManager(channelName);
  }
  return instance;
};